package com.share.service.impl;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.web.domain.AjaxResult;
import com.share.domain.MySql.Cabinet;
import com.share.domain.MySql.Station;
import com.share.domain.MongoDB.StationLocation;
import com.share.feign.FeeRuleFeignClient;
import com.share.repository.StationLocationRepository;
import com.share.service.ICabinetService;
import com.share.service.RegionService;
import com.share.service.StationService;
import com.share.mapper.StationMapper;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 肆
 * @description 针对表【station(站点表)】的数据库操作Service实现
 * @createDate 2025-03-25 19:00:12
 */
@Service
@Slf4j
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {

    @Autowired
    StationMapper stationMapper;

    @Autowired
    ICabinetService iCabinetService;

    @Autowired
    RegionService regionService;

    @Autowired
    ICabinetService cabinetService;

    @Autowired
    StationLocationRepository stationLocationRepository;

    //远程调用
    @Autowired
    FeeRuleFeignClient feeRuleFeignClient;


    /**
     * 分页查询站点列表
     *
     * @param station
     * @return
     */
    @Override
    public List<Station> selectStationList(Station station) {
        // 调用mapper方法获取站点列表
        List<Station> stationList = stationMapper.selectStationList(station);
        if (CollectionUtils.isEmpty(stationList)) {
            return stationList;
        }

        // 遍历站点列表，封装柜机编号和费用规则信息
        for (Station sta : stationList) {
            // 处理柜机编号
            Long cabinetId = sta.getCabinetId();
            if (cabinetId == null) {
                continue;
            }
            Cabinet cabinet = iCabinetService.getById(cabinetId);
            if (cabinet != null && cabinet.getCabinetNo() != null) {
                sta.setCabinetNo(cabinet.getCabinetNo());
            }

            // 处理费用规则
            Long feeRuleId = sta.getFeeRuleId();
            if (feeRuleId != null) {
                try {
                    AjaxResult info = feeRuleFeignClient.getInfo(feeRuleId);
                    if (info != null && info.isSuccess()) {
                        Object data = info.get(AjaxResult.DATA_TAG);
                        // 假设返回数据为费用规则对象，根据实际类型转换（示例：FeeRule为假设的数据类型）
                            Map<String, Object> dataMap = (Map<String, Object>) data;
                            String descriptionValue = (String) dataMap.get("description");
                            // 使用获取到的值，例如封装到 sta 对象（假设 Station 类有对应属性）
                            if (descriptionValue != null) {
                                sta.setFeeRuleName(descriptionValue); // 假设 Station 类有 setDescription 方法
                            }
                    } else {
                        String errorMsg = info != null ? (String) info.get(AjaxResult.MSG_TAG) : "远程调用无响应";
                        log.error("获取费用规则信息失败，id：{}，原因：{}", feeRuleId, errorMsg);
                    }
                } catch (Exception e) {
                    log.error("调用费用规则远程接口异常，id：{}", feeRuleId, e);
                }
            }
        }

        return stationList;
    }


    /**
     * 新增站点
     *
     * @param station
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveStation(Station station) {
        String provinceName = regionService.getNameByCode(station.getProvinceCode());//省
        String ccityName = regionService.getNameByCode(station.getCityCode());//市
        String districtName = regionService.getNameByCode(station.getDistrictCode());//县/区
        //插入完整地址
        station.setFullAddress(provinceName + ccityName + districtName + station.getAddress());
        this.save(station);

        //同步站点位置信息到MongoDB
        StationLocation stationLocation = new StationLocation();
        stationLocation.setId(ObjectId.get().toString());
        stationLocation.setStationId(station.getId());
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        stationLocation.setCreateTime(new Date());
        stationLocationRepository.save(stationLocation);
        return 1;
    }


    /**
     * 修改站点
     *
     * @param station
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateStation(Station station) {
        String provinceName = regionService.getNameByCode(station.getProvinceCode());//省
        String ccityName = regionService.getNameByCode(station.getCityCode());//市
        String districtName = regionService.getNameByCode(station.getDistrictCode());//县/区
        //插入完整地址
        station.setFullAddress(provinceName + ccityName + districtName + station.getAddress());
        //修改数据库站点信息
        this.updateById(station);

        // 查询 MongoDB 中对应的 StationLocation 记录
        StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());

        if (stationLocation == null) {
            // 如果不存在，则创建一个新的 StationLocation 对象
            stationLocation = new StationLocation();
            stationLocation.setStationId(station.getId()); // 设置关联的 stationId
        }
        // 设置地理位置信息
        stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
        // 保存到 MongoDB
        stationLocationRepository.save(stationLocation);
        return 1;
    }


    /**
     * 站点设置关联数据
     *
     * @param station
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int setData(Station station) {
        this.updateById(station);

        //更正柜机使用状态
        Cabinet cabinet = cabinetService.getById(station.getCabinetId());
        cabinet.setStatus("1");
        cabinetService.updateById(cabinet);
        return 1;
    }


    /**
     * 批量删除MongoDB站点
     *
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<?> list) {
        System.out.println("removeByIds called by:");
        Thread.dumpStack(); // 打印调用栈
        for (Object id : list) {
            stationLocationRepository.deleteByStationId(Long.parseLong(id.toString()));
        }
        //复用父方法
        return super.removeByIds(list);
    }


    /**
     * 更新初始化数据MongoDB
     */
    @Override
    public void updateData() {
        //获取全部站点信息
        List<Station> stationList = this.list();
        //遍历每个站点
        for (Station station : stationList) {
            //根据站点ID获取站点位置信息
            StationLocation stationLocation = stationLocationRepository.getByStationId(station.getId());
            //如果站点位置信息存在，则创建新的站点位置信息并保存
            if (stationLocation != null) {
                stationLocation = new StationLocation();
                stationLocation.setId(ObjectId.get().toString());
                stationLocation.setStationId(station.getId());
                stationLocation.setLocation(new GeoJsonPoint(station.getLongitude().doubleValue(), station.getLatitude().doubleValue()));
                stationLocation.setCreateTime(new Date());
                stationLocationRepository.save(stationLocation);
            }
        }
    }



}




